#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <functional>


#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"


static const uint16_t gport = 8080;
using handler_t = std::function<std::string(std::string&)>;
#define BACKLOG 8
using namespace LogModule;
using namespace ThreadPoolModule;

class TcpServer
{
    using task_t = std::function<void()>;
    
public:
    TcpServer(handler_t handler,int port = gport):
        _handler(handler),
        _port(port),
        _isrunning(false)
    {

    }
    void InitServer()
    {
        //1.创建TCP套接字
        _listensockfd = ::socket(AF_INET,SOCK_STREAM,0);
        if(_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket create success, sockfd is : " << _listensockfd;
        
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(gport);
        local.sin_addr.s_addr = INADDR_ANY;
        //2.bind
        int n = ::bind(_listensockfd,CONV(&local),sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success...";
        //3.cs,tcp是面向链接的,就要求tcp随时随地等待被链接
        //tcp 需要将我们的套接字设置为监听状态
        n = ::listen(_listensockfd,BACKLOG);
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success...";

        //子进程退出最好的做法
        // ::signal(SIGCHLD,SIG_IGN);//子进程退出,OS会自动回收资源,不用再进行wait了
    }
    void HandlerRequest(int sockfd)
    {
        char inbuffer[4096];
        std::string package;
        //长任务
        while(true)
        {
            //约定: 用户发过来的是一个完整的命令string
            ssize_t n = recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);
            if(n > 0)
            {
                inbuffer[n] = 0;
                LOG(LogLevel::INFO) << "\n" << inbuffer;
                package += inbuffer;
                //package  ->  len\r\n{json}\r\n......
                //cmd_str  ->  len\r\n{json}\r\n
                std::string cmd_result = _handler(package);
                if(cmd_result.empty())
                {
                    continue;
                }

                ::send(sockfd,cmd_result.c_str(),cmd_result.size(),0);
            }
            else if(n == 0)
            {
                // read 如果读取返回值是0,标识client退出
                LOG(LogLevel::INFO) << "client exit: " << sockfd;
                break;
            }
            else
            {
                //读取失败了
                break;
            }
        }
        ::close(sockfd);
    }
    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            //不能直接读数据
            //1.获取新连接
            struct sockaddr_in peer;
            socklen_t peerlen = sizeof(peer);
            LOG(LogLevel::DEBUG) << "accept ing...";
            int sockfd = ::accept(_listensockfd,CONV(&peer),&peerlen);
            if(sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error: " << strerror(errno);
                continue;
            }
            //2.获取链接成功
            LOG(LogLevel::INFO) << "accept success,sockfd is : " << sockfd;
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "client info: " << addr.Addr();
            
            //3.线程池处理我们对应的任务
            ThreadPool<task_t>::getInstance()->Equeue([this,sockfd](){
                this->HandlerRequest(sockfd);
            });
        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~TcpServer()
    {

    }
private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;

    //处理上层任务的入口
    handler_t _handler;
};


